package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import utils.BlockUtils;
import utils.FileInfo;
import utils.FileType;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length == 0) {
			System.out.println("No args");
			System.exit(0);
		}
		String path = args[0];
		File superBlob = BlockUtils.findSuperBlob(path);
		if(superBlob == null)
			System.exit(1);
		System.out.println(superBlob.length());
		if(checkEmpty(superBlob)) {
			System.out.println("SuperBlob is empty. Initialazing");
			System.out.println(superBlob.length());
			File writeToFile = BlockUtils.writeToFile(FileType.CATALOGUE_TYPE, superBlob.getName(), superBlob, 0);
			FileInfo fileInfo = BlockUtils.getFileInfo(writeToFile);
			System.out.println(fileInfo);
		} else {
			System.out.println("SuperBlob is empty. Initialazing");
		}
	}
	
	/**
	 * Проверяем есть ли уже система или ещё нет.(создан ли суперблоб)
	 * @param f
	 * @return
	 */
	private static boolean checkEmpty(File f) {
		if (!f.canRead())
		try {
			throw new FileNotFoundException("Can't read file " + f.getAbsolutePath());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(0);
		}
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(f);
			long length = f.length();
			System.out.println(length);
			byte[] b = new byte[(int) length];
			for(int i = 0; i < b.length - 1; i++) {
				if(b[i] == 0)
					continue;
				else
					return false;
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				fin.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
		System.exit(0);
		return false;
	}
}
